package com.pai4j.aigc.controller;
import com.pai4j.aigc.service.PlantUmlService;
import com.pai4j.common.bean.PAIResponseBean;
import com.pai4j.common.bean.PAIResponseBeanUtil;
import com.pai4j.common.service.MinioService;
import com.pai4j.common.util.IDGenerateUtil;
import com.pai4j.common.util.DateUtils;
import com.pai4j.domain.vo.response.UploadResultVO;
import com.pai4j.log.annotation.OperationLog;
import com.pai4j.remote.aigc.PlantUmlClient;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *   plantUmlController
 *
 * @author: CYM-pai
 * @date: 2025/05/31 19:47
 **/
@Slf4j
@RestController
public class PlantUmlController implements PlantUmlClient {
    
    @Resource
    private PlantUmlService plantUmlService;
    
    @Resource
    private MinioService minioService;
    
    
    // 图片存储路径
    private static final String PLANTUML_IMAGE_PATH = "plantuml/images/";
    
    /**
     * 生成PNG图片并上传到MinIO
     */
    @PostMapping(value = "/aigc-service/plantUml/png", produces = MediaType.APPLICATION_JSON_VALUE)
    @OperationLog(
        module = "AIGC管理",
        operation = "生成PNG图片",
        description = "用户生成PlantUML PNG图片",
        recordParams = false
    )
    public PAIResponseBean<Map<String, Object>> generatePng(@RequestBody String plantUmlCode) {
        try {
            // 生成PNG图片
            byte[] imageBytes = plantUmlService.generatePng(plantUmlCode);
            
            // 生成文件名
            String fileName = generateFileName("png");
            
            // 上传图片到MinIO
            UploadResultVO uploadResult = uploadByteArrayToMinio(imageBytes, fileName, "image/png");
            if (uploadResult == null) {
                return PAIResponseBeanUtil.error(500, "上传PNG图片到MinIO失败");
            }
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("imageUrl", uploadResult.getUrl());
            result.put("fileName", fileName);
            result.put("plantUmlCode", plantUmlCode);
            
            return PAIResponseBeanUtil.success(result);
        } catch (IOException e) {
            log.error("生成PNG图片失败", e);
            return PAIResponseBeanUtil.error(500, "生成PNG图片失败: " + e.getMessage());
        }
    }
    
    /**
     * 生成SVG并上传到MinIO
     */
    @PostMapping(value = "/aigc-service/plantUml/svg", produces = MediaType.APPLICATION_JSON_VALUE)
    @OperationLog(
        module = "AIGC管理",
        operation = "生成SVG图片",
        description = "用户生成PlantUML SVG图片",
        recordParams = false
    )
    public PAIResponseBean<Map<String, Object>> generateSvg(@RequestBody String plantUmlCode) {
        try {
            // 生成SVG
            String svgContent = plantUmlService.generateSvg(plantUmlCode);
            
            // 生成文件名
            String fileName = generateFileName("svg");
            
            // 将SVG内容转换为字节数组并上传到MinIO
            byte[] svgBytes = svgContent.getBytes(StandardCharsets.UTF_8);
            UploadResultVO uploadResult = uploadByteArrayToMinio(svgBytes, fileName, "image/svg+xml");
            if (uploadResult == null) {
                return PAIResponseBeanUtil.error(500, "上传SVG到MinIO失败");
            }
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("imageUrl", uploadResult.getUrl());
            result.put("fileName", fileName);
            // 同时返回SVG内容，方便前端直接嵌入
            result.put("svgContent", svgContent);
            result.put("plantUmlCode", plantUmlCode);
            
            return PAIResponseBeanUtil.success(result);
        } catch (IOException e) {
            log.error("生成SVG失败", e);
            return PAIResponseBeanUtil.error(500, "生成SVG失败: " + e.getMessage());
        }
    }
    
    /**
     * 生成ASCII文本
     */
    @PostMapping(value = "/aigc-service/plantUml/ascii", produces = MediaType.TEXT_PLAIN_VALUE)
    public PAIResponseBean<String> generateAscii(@RequestBody String plantUmlCode) {
        try {
            String asciiContent = plantUmlService.generateAscii(plantUmlCode);
            return PAIResponseBeanUtil.success(asciiContent);
        } catch (IOException e) {
            log.error("生成ASCII文本失败", e);
            return PAIResponseBeanUtil.error(500, "生成ASCII文本失败: " + e.getMessage());
        }
    }
    

    
    /**
     * 生成唯一文件名
     */
    private String generateFileName(String extension) {
        String dateStr = DateUtils.getDate2String(DateUtils.YYYYMMDD, new Date());
        String uuid = IDGenerateUtil.uuid().substring(0, 8);
        return dateStr + "_" + uuid + "." + extension;
    }
    
    /**
     * 将字节数组上传到MinIO
     */
    private UploadResultVO uploadByteArrayToMinio(byte[] data, String fileName, String contentType) {
        try {
            // 构建文件完整路径
            String timePackage = DateUtils.getDate2String(DateUtils.YYYYMMDD, new Date());
            String fullPath = PLANTUML_IMAGE_PATH + timePackage + "/";
            
            // 创建MultipartFile对象
            MultipartFile file = new MockMultipartFile(fileName, fileName, contentType, data);
            
            // 使用MinioService上传
            return minioService.upload(fullPath, file, true);
        } catch (Exception e) {
            log.error("上传图片到MinIO失败", e);
            return null;
        }
    }
}
